package oj.hot100;

public class 分割等和子集 {
    //01背包问题,优化前
    public boolean canPartitionPre(int[] nums) {
        int n = nums.length,target = 0,sum = 0;
        for(int num : nums) {
            sum += num;
        }
        target = sum/2;
        //如果和为奇数的话那就不存在等和子集.
        if(sum % 2 == 1) {
            return false;
        }
        boolean[][] dp = new boolean[n+1][target+1];
        dp[0][0] = true;
        for(int i = 1;i <= n;i++) {
            for(int j = 0;j <= target;j++) {
                dp[i][j] = dp[i-1][j];
                if(j >= nums[i-1]) {
                    dp[i][j] = dp[i][j] || dp[i-1][j-nums[i-1]];
                }
            }
        }
        return dp[n][target];
    }
    //优化后
    public boolean canPartition(int[] nums) {
        int n = nums.length,target = 0,sum = 0;
        for(int num : nums) {
            sum += num;
        }
        target = sum/2;
        //如果和为奇数的话那就不存在等和子集.
        if(sum % 2 == 1) {
            return false;
        }
        boolean[] dp = new boolean[target+1];
        dp[0] = true;
        for(int i = 1;i <= n;i++) {
            for(int j = target;j >= nums[i-1];j--) {
                dp[j] = dp[j] || dp[j-nums[i-1]];
            }
        }
        return dp[target];
    }
}
